#include "stm32f4xx_rcc.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_exti.h"
#include "stm32f4xx_pwr.h"
#include "stm32f4xx_syscfg.h"
#include "misc.h"

#include "func.h"
#include "utils.h"

static __IO u8 checked = 0;

static void StandbyMode(void)
{
    //RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);
    PWR_WakeUpPinCmd(ENABLE);
    PWR_EnterSTANDBYMode();
}

void CheckButton(void)
{
    if (checked) {
        DelayMs(1000);
        if (checked)
            StandbyMode();
    }
}

void WKUPInit(void)
{
    GPIO_InitTypeDef gpioInitStruct;
    EXTI_InitTypeDef extiInitStruct;
    NVIC_InitTypeDef nvicInitStruct;

    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
    gpioInitStruct.GPIO_Mode = GPIO_Mode_IN;
    gpioInitStruct.GPIO_PuPd = GPIO_PuPd_UP;
    gpioInitStruct.GPIO_Pin = GPIO_Pin_0;
    GPIO_Init(GPIOA, &gpioInitStruct);

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
    SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOF, EXTI_PinSource13);

    extiInitStruct.EXTI_Line = EXTI_Line13;
    extiInitStruct.EXTI_Mode = EXTI_Mode_Interrupt;
    extiInitStruct.EXTI_Trigger = EXTI_Trigger_Rising_Falling;
    extiInitStruct.EXTI_LineCmd = ENABLE;
    EXTI_Init(&extiInitStruct);

    nvicInitStruct.NVIC_IRQChannel = EXTI15_10_IRQn;
    nvicInitStruct.NVIC_IRQChannelPreemptionPriority = 0;
    nvicInitStruct.NVIC_IRQChannelSubPriority = 0;
    nvicInitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&nvicInitStruct);
}

void EXTI15_10_IRQHandler(void)
{
    if (EXTI_GetITStatus(EXTI_Line13) == SET) {
        if (!KEY1)
            checked = 1;
        else
            checked = 0;
        EXTI_ClearITPendingBit(EXTI_Line13);
    }
}
